from django import http
from django.core.paginator import Paginator
from django.shortcuts import render, redirect
from django.views import View

from organization.models import Teacher
from teachers.form import TeacherForm
from utils import constants


class TeachersView(View):
    """
    teacher视图
    """

    def get(self, request):
        """
        返回teacher页面
        :param request:
        :return:
        """
        # 获取课程查询集
        teachers = Teacher.objects.all().order_by('-fav_nums')
        sorted_teacher = teachers[0:2]
        # 定义分页器
        # 创建分页器：每页N条记录
        paginator = Paginator(teachers, constants.COURSE_LIST_LIMIT)
        # 获取当前页
        pageNum = request.GET.get('page', 1)
        # 获取每页商品数据
        try:
            teachers_list = paginator.page(pageNum)
        except:
            # 如果page_num不正确，默认给用户404
            return http.HttpResponseNotFound('empty page')
        teachers_list.pages = [i for i in range(1, paginator.num_pages + 1)]
        return render(request, 'teachers-list.html', {'all_teachers': teachers_list, 'sorted_teacher': sorted_teacher})


class TeacherDetailView(View):
    """
    教师详情视图
    """

    def get(self, request, pk):
        try:
            teacher = Teacher.objects.get(id=pk)
            all_courses = teacher.course_set.all()
        except:
            return redirect('/teacher/')

        return render(request, 'teacher-detail.html', {'teacher': teacher,'all_courses':all_courses})
